<?php

use app\server\Upload;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
use think\exception\HttpResponseException;
use think\Response;

// 应用公共文件
/**
 * 数据压缩
 * @param array $str
 * @return string
 */
function arrayToCompress(array $result) {
    return base64_encode(gzdeflate(json_encode($result, 256), 9));
}

/**
 * 数据解压
 * @param string $str
 * @return mixed
 */
function compressToArray(string $str){
    return json_decode(gzinflate(base64_decode($str)),true);
}
/**
 * 返回成功信息JSON
 * @param string $msg
 * @param int $code
 * @param array $data
 */
function success(string $msg = 'success', array $data = [], int $count = 0, int $code = 200) {
    $result = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
        'count' => $count
    ];
//    $result = arrayToCompress($result);
    return json($result);
}

/**
 * 返回失败JSON
 * @param string $msg
 * @param int $code
 * @param array $data
 */
function error(string $msg = 'error', int $code = 0, array $data = []) {

    $result = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
//    $result = arrayToCompress($result);
    return json($result);
}

/**
 * 根据json web token设置的规则生成token
 * @param $uid
 * @return string
 */
function createJwt($user) {
    $key = md5('laopifu');   //jwt的签发密钥，验证token的时候需要用到
    $time = time();          //签发时间
    $expire = $time + 86400; //过期时间
    $token = [
        "iss" => "laopifu",//签发组织
        "aud" => "laopifu", //签发作者
        "iat" => $time,
        "nbf" => $time,
        "exp" => $expire
    ];
    $token = array_merge($user, $token);
    return JWTUtil::encode($token, $key);
}

/**
 * 验证token
 * @param $jwt
 * @return array
 */
function verifyJwt($jwt) {
    $key = md5('laopifu'); //jwt的签发密钥，验证token的时候需要用到
    try {
        $jwtAuth = json_encode(JWTUtil::decode($jwt, $key, ["HS256"]));
        $authInfo = json_decode($jwtAuth, true);
        return ['code' => 1, 'msg' => 'ok', 'data' => $authInfo];
    } catch (ExpiredException $e) {
        return ['code' => 0, 'msg' => 'token过期'];
    } catch (\Exception $e) {
        return ['code' => 0, 'msg' => $e->getMessage()];
    }

}

/**
 * 获取当前访问
 * @param $request
 * @return array
 */
function nowUrl($request) {
    $module = strtolower(app('http')->getName());
    $controller = strtolower($request->controller());
    $action = strtolower($request->action());
    return ['module' => $module, 'controller' => $controller, 'action' => $action];
}

/**
 * 数组查询
 * @param $key
 * @param $val
 * @param $data
 * @return array
 */
function arrayModel($key, $val, $data) {
    $result = array_filter($data, function ($where) use ($key, $val) {
        return $where[$key] == $val;
    });
    return $result;
}
function arrayInModel($key, $in_val, $array_data) {
    if (!is_array($in_val)) {
        $in_val=explode(',',$in_val);
    }
    $data=[];
    foreach ($in_val as $value){
        $result = array_filter($array_data, function ($where) use ($key, $value) {
            return $where[$key] == $value;
        });
        foreach ($result as $val){
            $data[]=$val;
        }
    }
    return $data;
}

/**
 * 生成随机数
 * @param int $type 1数字2大小写字母3大写字母4数字+大小写字母
 * @param int $length
 * @return false|string
 */
function rand_code($type = 1, $length = 6) {
    $chars_a = "abcdefghijklmnopqrstuvwxyz";
    $chars_A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $chars_1 = "0123456789";
    switch ($type) {
        case 1:
            $chars = $chars_1;
            break;
        case 2:
            $chars = $chars_a . $chars_A;
            break;
        case 3:
            $chars = $chars_A;
            break;
        case 4:
            $chars = $chars_1 . $chars_a . $chars_A;
            break;
        default:
            $chars = '';
            break;
    }
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return substr($str, 0, $length);
}

/**
 * 生成密码
 * @param string $password
 * @param int $uid
 * @return string
 */
function makePassword(string $password, int $uid = 0) {
    return md5(md5($password . $uid . $password));
}

/**
 * 验证密码
 * @param string $password
 * @param int $uid
 * @param string $oldPassword
 * @return bool
 */
function checkPassword(string $password, int $uid = 0, string $oldPassword) {
    if ($oldPassword == md5(md5($password . $uid . $password))) {
        return true;
    }
    return false;
}

/**
 * 处理列表请求数据
 * @return array
 */
function getData() {
    $request=input();
    $page = $request['page'] ?? 1;
    $limit = $request['limit'] ?? 15;
    unset($request['limit'], $request['page']);
    $where = $request;
    foreach($request as $k=>$v){
        if($v===''){
            unset($where[$k]);
        }
    }
    return [$where, intval($page), intval($limit)];
}

/**
 *上传内容图片
 */
function uploadFile() {
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('file');
    $savePath = new Upload($file);
    return $savePath->UpFile();
}
